<template>
  <div class="content-table">
    <div class="table-header">
      <div class="oper">
        <slot name="oper"> </slot>
      </div>

      <a-button type="primary">
        <template #icon><align-center-outlined /></template>
      </a-button>
    </div>

    <div class="main">
      <a-table
        :columns="contentTableParam.data.columns"
        :rowKey="contentTableParam.data.rowKey || 'key'"
        :data-source="contentTableParam.data.dataSource"
        :loading="contentTableParam.data.loading"
        :scroll="contentTableParam.data.scroll"
        :pagination="false"
        :row-selection="
          contentTableParam.data.rowSelection
            ? {
                onSelectAll: selectAllHandle,
                selectedRowKeys: selectedRowKeys,
                type: contentTableParam.data.rowSelectionType || 'checkbox',
                columnTitle: contentTableParam.data.rowSelectionColumnTitle || '',
                onChange: selectChangeHandle,
                onSelect: rowSelectionHandle,
                getCheckboxProps: getCheckboxProps,
                fixed: contentTableParam.data.fixed ? true : false,
                columnWidth: contentTableParam.data.columnWidth || 80,
              }
            : null
        "
        :showHeader="contentTableParam.data.showHeader || true"
        :rowClassName="(record: any, index: number) => (index % 2 === 1 ? `${contentTableParam.data.rowClassName || ''} table-striped` : contentTableParam.data.rowClassName || '')"
        :expandFixed="contentTableParam.data.expandFixed || false"
        :expandedRowKeys="contentTableParam.data.expandedRowKeys || []"
        :expandRowByClick="contentTableParam.data.expandRowByClick || false"
        :childrenColumnName="contentTableParam.data.childrenColumnName || 'children'"
        @expandedRowsChange="expandedRowsHandle"
        @resizeColumn="resizeColumnHandle"
        @change="tableChangeHandle"
        bordered
      >
        <!--  Title -->
        <template #title="row" v-if="contentTableParam.data.isSlotOption && contentTableParam.data.isSlotOption.includes('title')"><slot name="title" :row="row"></slot></template>
        <!--  个性化头部单元格  -->
        <template #headerCell="row"><slot name="headerCell" :row="row"></slot></template>
        <!--  个性化单元格	 -->
        <template #bodyCell="row"><slot name="bodyCell" :row="row"></slot></template>
        <!--  表格尾部  -->
        <template #footer v-if="contentTableParam.data.isSlotOption && contentTableParam.data.isSlotOption.includes('footer')"><slot name="footer"></slot></template>
        <!--  合计行  -->
        <template #summary v-if="contentTableParam.data.isSlotOption && contentTableParam.data.isSlotOption.includes('summary')"><slot name="summary"></slot></template>
        <!--  数据为空  -->
        <template #emptyText v-if="contentTableParam.data.isSlotOption && contentTableParam.data.isSlotOption.includes('emptyText')"><slot name="emptyText"></slot></template>
        <!--  额外的展开行  -->
        <template #expandedRowRender="row" v-if="contentTableParam.data.isSlotOption && contentTableParam.data.isSlotOption.includes('expandedRowRender')"><slot name="expandedRowRender" :row="row"></slot></template>
        <!--  额外的展开行  -->
        <template #expandIcon="row" v-if="contentTableParam.data.isSlotOption && contentTableParam.data.isSlotOption.includes('expandIcon')"><slot name="expandIcon" :row="row"></slot></template>
      </a-table>
      <div class="main-page" v-if="contentTableParam.data.pagination">
        <div class="selectTotal" v-if="contentTableParam.data.rowSelection">已选{{ selectedRowKeys.length }}条<slot name="allSelect"></slot></div>
        <div class="ResetSelected" v-if="contentTableParam.data.isResetSelected" @click="resetSelectedHandle">清空已选</div>
        <a-pagination v-model:current="contentTableParam.data.pagination.current" :pageSize="contentTableParam.data.pagination.pageSize" @change="paginationChange" :total="contentTableParam.data.pagination.total" :pageSizeOptions="contentTableParam.data.pagination.pageSizeOptions" :showTotal="contentTableParam.data.pagination.showTotal" show-less-items showSizeChanger />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { AlignCenterOutlined } from '@ant-design/icons-vue'

import type { IContentTable } from '@/types/interface/content'
interface IProps {
  tableParam: IContentTable
}

const _props = withDefaults(defineProps<IProps>(), {
  tableParam: () => ({
    name: '',
    rowKey: 'id',
    columns: [],
    dataSource: [],
    selectedRowKeys: [],
    disabledRowKeys: [],
  }),
})

const _emits = defineEmits(['paginationHandle', 'rowSelectionHandle', 'selectAllHandle', 'expandedRowOpenHandle', 'tableChangeHandle', 'customRowClickHandle', 'resetSelectedHandle'])

/**表格配置 */
const contentTableParam = reactive<{ data: IContentTable }>({
  data: {
    name: '',
    columns: [],
    dataSource: [],
    pagination: {
      pageSize: 1,
    },
  },
})

const initTable = () => {
  contentTableParam.data = _props.tableParam
}

const activeKey = ref()
const pageSelectKeys = ref({})
const selectedRowKeys = ref<string[]>([])

const selectAllHandle = (selected: boolean, selectedRows: any[], changeRows: any[]) => {
  activeKey.value = {
    type: 'all',
    selectedRows: selectedRows,
    selected: selected,
    changeRows: changeRows,
  }
  console.log('activeKey.value', activeKey.value)
}

/**
 * @method 开启复选框之后，选中
 */
const selectChangeHandle = (keys: Array<string>, items: Array<any>) => {
  if (contentTableParam.data.rowSelectionType === 'radio') {
    // 单选
    setTimeout(() => {
      _emits('rowSelectionHandle', keys, items)
    }, 0)
    selectedRowKeys.value = keys
  } else {
    // 多选
    let keyList: Array<string> = [],
      itemList: Array<any> = []
    pageSelectKeys.value[contentTableParam.data.pagination?.current || 0] = { items: items, keys: keys }

    for (const i in pageSelectKeys.value) {
      keyList = keyList.concat(pageSelectKeys.value[i].keys)
      itemList = itemList.concat(pageSelectKeys.value[i].items)
    }

    // 禁用keys和selectKey可能会有相同数据
    selectedRowKeys.value = [...new Set(keyList.concat((contentTableParam.data.disabledRowKeys as string[]) || []))]
    setTimeout(() => {
      _emits('rowSelectionHandle', selectedRowKeys.value, itemList, activeKey.value)
      activeKey.value = {}
    }, 0)
  }
}

/**
 * @method 开启复选框之后，选中
 */
const rowSelectionHandle = (record: any, selected: any) => {
  activeKey.value = {
    record: record,
    selected: selected,
  }
}

/**
 *@method 复选/单选禁用对象
 */
const getCheckboxProps = (record: any) => {
  const key = contentTableParam.data.rowKey
  if (contentTableParam.data.rowSelection && !key) {
    console.error('请传入rowKey')
  }
  const _item = typeof key === 'string' ? record[key]?.trim() : key
  return {
    disabled: contentTableParam.data.disabledRowKeys ? contentTableParam.data.disabledRowKeys.includes(_item) : false,
    name: record.name,
  }
}

/**
 * @method 展开的行变化时触发
 */
const expandedRowsHandle = (row: any) => {
  contentTableParam.data.expandedRowKeys = row
  _emits('expandedRowOpenHandle', row)
}

/**
 * @method 拖动列
 */
const resizeColumnHandle = (w: number, col: any) => {
  col.width = w
}

/**
 * @method tableChange
 */
const tableChangeHandle = (...agm: any) => {
  _emits('tableChangeHandle', agm)
}

const resetSelectedHandle = () => {
  pageSelectKeys.value = {}
  selectedRowKeys.value = []
  _emits('resetSelectedHandle')
}

/**
 * @method 分页改变
 */
const paginationChange = (page: any, pageSize: any) => {
  contentTableParam.data.pagination!.current = page
  contentTableParam.data.pagination!.pageSize = pageSize
  _emits('paginationHandle', {
    current: page,
    pageSize: pageSize,
  })
}

onMounted(() => {
  initTable()
})
</script>

<style lang="less" scoped>
.table-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 65px;
  .oper {
    width: 100%;
  }
}
.content-table {
  width: 100%;
  height: 100%;
  .main {
    padding: 0 15px;
    display: flex;
    flex-direction: column;
    height: calc(100% - 65px);
    .main-page {
      display: flex;
      padding: 15px;
      // justify-content: flex-end;
      align-items: center;
      line-height: 31px;
    }
    .selectTotal {
      margin-top: 10px;
      // margin-right: auto;
      display: flex;
    }
    .ResetSelected {
      margin-top: 10px;
      margin-left: 10px;
      // margin-right: auto;
      cursor: pointer;
      color: #3d7cff;
      transition: all 0.3s;
      &:hover {
        color: #1890ff;
      }
    }
    .ant-pagination {
      margin-left: auto;
    }
  }
}
.table-config-modal {
  padding: 10px;
  overflow: hidden;
  .table-config-container {
    overflow-y: scroll;
  }
  .col {
    border-left: 1px solid #ededed;
    tr {
      display: flex;
    }
    td {
      padding: 0 16px;
      height: 40px;
      width: 152.41px;
      line-height: 40px;
      border-bottom: 1px solid #ededed;
      border-right: 1px solid #ededed;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .col-item {
      display: flex;
      align-items: center;
      margin-right: 10px;

      .name {
        padding: 0 8px;
      }
      &:nth-child(1) {
        margin-right: auto;
      }
    }
    &:nth-child(1) {
      margin-top: 0;
    }
  }
  .col-header {
    border-top: 1px solid #ededed;
    border-right: 1px solid #ededed;
    border-bottom: 1px solid #ededed;
    background-color: #f3f7fa;
    td {
      border-bottom: none;
    }
  }
}
</style>

<style lang="less">
.ys-modal-0 {
  .ant-modal-body {
    overflow: hidden;
  }
}
</style>
